from typing import Optional

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from typing import List
from tools.db_tool import get_menu_items_list
from service.order_snap_service import smart_chat,delivery_check

# 定义 fastApi实例
app = FastAPI(title="OrderSnap", description="这是一个智能点餐小助手", version="1.0")


# 定义请求数据模型
class ChatRequest(BaseModel):
    query: str = Field(description="用户的原始输入")

class DeliveryRequest(BaseModel):
    """配送查询请求"""
    address: str
    travel_mode: Optional[int] = 3  # 1=直线, 2=驾车, 3=骑行

# 定义响应数据模型
class ChatResponse(BaseModel):
    """定义聊天请求模型"""
    success: bool  # 成功标识
    query: str  # 原始的请求输入
    response: Optional[str] = None  # 模型的输出
    recommendation: Optional[str] = None  # 推荐内容输出
    menu_ids: Optional[List[str]] = None

class DeliveryResponse(BaseModel):
    """配送查询响应"""
    success: bool
    in_range: bool #  配送是否在配送范围内
    distance: float # 配送距离
    formatted_address: str # 格式化地址
    message: str
    travel_mode: int # 配送模式
    input_address: str # 输入原始内容


class MenuListResponse(BaseModel):
    """定义菜品列表响应模型"""
    success: bool  # 成功标识
    menu_items: List[dict]  # 菜品列表
    count: int  # 菜品数量
    message: str


# 定义根路由
@app.get("/")
async def root():
    return {"message": "欢迎来到 OrderSnap 智能点单系统！！！"}


# 定义聊天的请求接口
@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
    """聊天接口"""
    print(f"原始输入:{request.query}")
    try:
        response = smart_chat(request.query)
        # 构建响应数据模型
        if isinstance(response, dict) and "recommendation" in response and "menu_ids" in response:
            return ChatResponse(success=True,
                                query=request.query,
                                recommendation=response["recommendation"],
                                menu_ids=response["menu_ids"])
        return ChatResponse(success=True, query=request.query, response=response)
    except HTTPException as e:
        raise HTTPException(status_code=500, detail=f"服务内部出错:{e.detail}")


# 定义配送范围检测的接口
@app.post("/delivery", response_model=DeliveryResponse)
async def delivery_endpoint(request: DeliveryRequest):
    """
    配送查询接口

    检查指定地址是否在配送范围内
    """
    try:
        # 调用配送查询服务
        result = delivery_check(request.address, request.travel_mode)

        if result["status"] == "success":
            return DeliveryResponse(
                success=True,
                in_range=result["in_range"],
                distance=result["distance"],
                formatted_address=result["formatted_address"],
                message=result["message"],
                travel_mode=request.travel_mode,
                input_address=request.address
            )
        else:
            return DeliveryResponse(
                success=False,
                in_range=False,
                distance=0.0,
                formatted_address=request.address,
                message=result["message"],
                travel_mode=request.travel_mode,
                input_address=request.address
            )

    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"配送查询服务失败: {str(e)}"
        )

# 定义菜品列表展示的请求接口
@app.get("/menu/list", response_model=MenuListResponse)
async def menu_list():
    """查询菜品列表的接口"""
    # 调用数据库的菜品列表信息
    item_list = get_menu_items_list()

    if not item_list:
        return MenuListResponse(success=False,
                                menu_items=[],
                                count=0,
                                message="没有查询到可用的菜品信息")

    # 判断构建返回对象
    return MenuListResponse(success=True,
                            menu_items=item_list,
                            count=len(item_list),
                            message="查询菜品列表")
